#!/bin/bash

# 二进制程序安装脚本
# 使用方法: sudo ./install_service.sh /path/to/binary [--args "arg1 arg2"] [--name service_name] [--description "Service Description"]

# 检查是否以root权限运行
if [ "$(id -u)" -ne 0 ]; then
    echo "请使用root权限运行此脚本 (使用sudo命令)"
    exit 1
fi

# 默认值
BINARY_PATH="./ttydx_amd64"
SERVICE_ARGS=""
SERVICE_NAME="ttydx"
SERVICE_DESC="ttydx service"
WORKING_DIR="/var/lib/"
USER="root"
GROUP="root"
RESTART="always"
RESTART_SEC="5"

# 解析命令行参数
while [[ $# -gt 0 ]]; do
    case $1 in
        --args)
            SERVICE_ARGS="$2"
            shift 2
            ;;
        --name)
            SERVICE_NAME="$2"
            shift 2
            ;;
        --description)
            SERVICE_DESC="$2"
            shift 2
            ;;
        *)
            if [ -z "$BINARY_PATH" ]; then
                BINARY_PATH="$1"
            else
                echo "未知参数: $1"
                exit 1
            fi
            shift
            ;;
    esac
done

# 检查二进制文件是否存在
if [ ! -f "$BINARY_PATH" ]; then
    echo "错误: 二进制文件 '$BINARY_PATH' 不存在"
    exit 1
fi

# 确定服务名称
if [ -z "$SERVICE_NAME" ]; then
    # 从二进制路径中提取文件名
    SERVICE_NAME=$(basename "$BINARY_PATH" | sed 's/\.[^.]*$//')
fi

# 确定工作目录
BASE_WORKING_DIR="${WORKING_DIR%/}/${SERVICE_NAME}"

# 复制二进制文件
TARGET_BINARY="/usr/local/bin/${SERVICE_NAME}"
echo "正在复制二进制文件到 $TARGET_BINARY..."
cp "$BINARY_PATH" "$TARGET_BINARY"
chmod +x "$TARGET_BINARY"

# 创建工作目录（如果不存在）
if [ ! -d "$BASE_WORKING_DIR" ]; then
    echo "正在创建工作目录 $BASE_WORKING_DIR..."
    mkdir -p "$BASE_WORKING_DIR"
    chown $USER:$GROUP "$BASE_WORKING_DIR"
fi

# 创建systemd服务文件
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"
echo "正在创建服务文件 $SERVICE_FILE..."
cat > "$SERVICE_FILE" << EOF
[Unit]
Description=$SERVICE_DESC
After=network.target

[Service]
ExecStart=$TARGET_BINARY $SERVICE_ARGS
WorkingDirectory=$BASE_WORKING_DIR
User=$USER
Group=$GROUP
Restart=$RESTART
RestartSec=$RESTART_SEC

[Install]
WantedBy=multi-user.target
EOF

# 重新加载systemd
echo "正在重新加载systemd配置..."
systemctl daemon-reload

# 启用并启动服务
echo "正在启用并启动服务..."
systemctl enable "$SERVICE_NAME"
systemctl start "$SERVICE_NAME"

# 检查服务状态
echo "正在检查服务状态..."
sleep 2
systemctl status "$SERVICE_NAME" --no-pager

echo "服务安装完成!"
echo "服务名称: $SERVICE_NAME"
echo "二进制路径: $TARGET_BINARY"
echo "工作目录: $BASE_WORKING_DIR"
echo "服务文件: $SERVICE_FILE"

echo -e "\n管理命令:"
echo "启动服务: systemctl start $SERVICE_NAME"
echo "停止服务: systemctl stop $SERVICE_NAME"
echo "重启服务: systemctl restart $SERVICE_NAME"
echo "查看状态: systemctl status $SERVICE_NAME"
echo "查看日志: journalctl -u $SERVICE_NAME -f"